package cn.wolfcode.producer._02_send_way;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

/**
 * @Author: 乱梦天真
 * @Description: TODO
 * @Date: 2020/5/10 11:44
 */
public class Producer1 {
    public static void main(String[] args) throws Exception {
        //1.新建一个生产者
        DefaultMQProducer producer = new DefaultMQProducer("wolfcode_producer");
        //2.绑定Namesrv
        producer.setNamesrvAddr("127.0.0.1:9876");
        //3.启动生产者
        producer.start();
        //线程等待
        CountDownLatch downLatch = new CountDownLatch(10);
        //4.新建消息
        for (int i = 0; i < 10 ; i++) {
            Message message = new Message("_02_send_way", "你好,rocketmq".getBytes("utf-8"));
            //5.发送消息
            //TODO 异步发送消息
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    //执行一次－1
                    downLatch.countDown();
                    System.out.println("发送成功");
                }

                @Override
                public void onException(Throwable throwable) {
                    downLatch.countDown();
                    System.out.println("发送失败");
                }
            });
        }
        //TODO 异步发送在事件回调完之前,生产者必须在线,否则发送失败
        downLatch.await();
        //6.关闭资源
        producer.shutdown();
    }
}